#include "packet.h"

uint32_t packet::VERSION = MAKE_WORD( 1, 1 );

uint32_t packet::PACKET_HEADER_SIZE = 3 * sizeof( int );

MemoryPool<char> *packet::buffer_pool = 0;

uint32_t packet::packet_count = 0;

packet::packet( uint32_t src, uint32_t dst )
{
	source.addr = src;
	destination.addr = dst;
	_type = Packet;
	packet_count++;
	curbuf = 0;

	if( buffer_pool == 0 )
		buffer_pool = new MemoryPool<char>( 1000, 256 );
}

packet::packet( uint32_t src, uint32_t dst, Packet_Type type ) : _type( type )
{
	source.addr = src;
	destination.addr = dst;
	packet_count++;
	curbuf = 0;

	if( buffer_pool == 0 )
		buffer_pool = new MemoryPool<char>( 1000, 256 );
}


packet::~packet(void)
{
	buffer_pool->destroy( curbuf );

	packet_count--;
	if( packet_count <= 0 )
	{
		delete buffer_pool;
		buffer_pool = 0;
	}
}

char *packet::serialize()
{
	curbuf = buffer_pool->create();

	*(uint8_t *)(curbuf + 0) = (uint8_t)(VERSION & 0xFF00 ) >> 4;
	*(uint8_t *)(curbuf + 1) = (uint8_t)(VERSION & 0x00FF );

	*(uint8_t *)(curbuf + 2) = (uint8_t)( (source.addr & 0xFF000000 ) >> 24 );
	*(uint8_t *)(curbuf + 3) = (uint8_t)( (source.addr & 0x00FF0000 ) >> 16 );
	*(uint8_t *)(curbuf + 4) = (uint8_t)( (source.addr & 0x0000FF00 ) >> 8 );
	*(uint8_t *)(curbuf + 5) = (uint8_t)( source.addr & 0x000000FF );

	*(uint8_t *)(curbuf + 6) = (uint8_t)( (destination.addr & 0xFF000000 ) >> 24 );
	*(uint8_t *)(curbuf + 7) = (uint8_t)( (destination.addr & 0x00FF0000 ) >> 16 );
	*(uint8_t *)(curbuf + 8) = (uint8_t)( (destination.addr & 0x0000FF00 ) >> 8 );
	*(uint8_t *)(curbuf + 9) = (uint8_t)( destination.addr & 0x000000FF );

	*(uint8_t *)(curbuf + 10) = (uint8_t)_type & 0xFF;

	return curbuf;
}

void packet::print()
{
	printf( "VERSION: %04X\nTYPE: %d\n", VERSION, _type );
}